package com.liuda066.forumssm.services.impl;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import com.liuda066.forumssm.dao.ArticleMapper;
import com.liuda066.forumssm.exception.ApplicationException;
import com.liuda066.forumssm.model.Article;
import com.liuda066.forumssm.model.Board;
import com.liuda066.forumssm.model.User;
import com.liuda066.forumssm.services.IArticleService;
import com.liuda066.forumssm.services.IBoardService;
import com.liuda066.forumssm.services.IUserService;
import com.liuda066.forumssm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/4 22:28
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Resource
    private IUserService iUserService;

    @Resource
    private IBoardService iBoardService;

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        if (boardId == null){
            log.info(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        List<Article> result = articleMapper.selectByBoardId(boardId);
        return result;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if (userId == null){
            log.info(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        return articleMapper.selectByUserId(userId);
    }

    @Override
    public List<Article> selectDetailsByContent(String content) {
        if (content == null || StringUtils.isEmpty(content)){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        List<Article> result = articleMapper.selectDetailsByContent(content);
        if (result==null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        return result;
    }

    @Override
    public void create(Article article) {
        if (article == null || article.getUserId() == null
                || article.getBoardId()==null || StringUtils.isEmpty(article.getTitle())
                || StringUtils.isEmpty(article.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0){
            log.warn(ResultCode.FAILED_CREATE.toString()+"受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        User user = iUserService.selectById(article.getUserId());
        if (user==null){
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败,找不到用户,userId = "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        iUserService.addOneArticleCountById(user.getId());

        Board board = iBoardService.selectById(article.getBoardId());
        if (board==null){
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败,找不到板块,boardId = "+article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        iBoardService.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString()+",userID:"+article.getUserId() +
                ",boardId:"+article.getBoardId()+"发帖成功.");
    }

    @Override
    public Article selectDetailById(Long id) {
        if (id == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        Article result = articleMapper.selectDetailsById(id);
        if (result==null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //更新访问次数
        Article update = new Article();
        update.setId(result.getId());
        update.setVisitCount(result.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId = "+result.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        result.setVisitCount(result.getVisitCount()+1);
        return result;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || StringUtils.isEmpty(title) || StringUtils.isEmpty(content )){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        Article update = new Article();
        update.setId( id);
        update.setTitle(title);
        update.setContent(content);
        update.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString() + "受影响的行数不等于 1 . articleId = "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        if (id == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        Article article = selectDetailById(id);
        if (article==null || article.getState() !=0  ||article.getDeleteState()!=0){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        Article update = new Article();
        update.setId(article.getId());
        update.setLikeCount(article.getLikeCount()+1);

        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row!=1){
            log.warn(ResultCode.FAILED_CREATE.toString()+"更新失败. userId = "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public void deleteById(Long id) {
        if (id == null || id <=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);
        if (article==null || article.getState() !=0  ){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        Article update = new Article();
        update.setId(article.getId());
        update.setDeleteState((byte) 1);

        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString()+"删除失败. articleId = "+article.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        iBoardService.subOneArticleCountById(article.getBoardId());
        iUserService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功， articleId = "+article.getId()+", userId = " + article.getUserId()+".");
    }
}
